package com.hspedu.object;

/**
 * @Author Stringzhua
 * @Date 2024/3/3 10:53
 * description:
 */
public class ToString_ {
    public static void main(String[] args) {
        /*Object的toString()源码
        * (1)(getClass().getName() 类的全类名(包名+类名)
        * (2)Integer.toHexString(hashCode() 将该对象的hashCode转成16进制字符串
        * public String toString() {
                return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }
        * */
        Monster monster = new Monster("小妖怪", "巡山", 1000);
//        System.out.println(monster.toString()+" hashCode="+monster.hashCode());//com.hspedu.object.Monster@4554617c hashCode=1163157884
        System.out.println(monster.toString() + " hashCode=" + monster.hashCode());

        //(4)当直接输出一个对象时,toString对象会被默认的调用,例如:
        System.out.println(monster);//等价于monster.toString()
    }
}

class Monster {
    private String name;
    private String job;
    private double sal;

    //(3)重写toString方法,打印对象或拼接对象时,都会自动调用该对象的toString形式
    //使用快捷键即可生成 alt+insert->toString
    @Override
    public String toString() {//重写后,一般是把对象的属性输出, 当然可以自己定制
        return "Monster{" +
                "name='" + name + '\'' +
                ", job='" + job + '\'' +
                ", sal=" + sal +
                '}';
    }

    public Monster(String name, String job, double sal) {
        this.name = name;
        this.job = job;
        this.sal = sal;
    }
}
